//
//  AppDelegate.m
//  QAir
//
//  Created by qkong on 15/6/12.
//  Copyright (c) 2015年 qkong. All rights reserved.
//

#import "QAirAppDelegate.h"

#import "Config.h"
#import "MainViewController.h"
#import "SideBarLeftViewController.h"
#import "UIView+Toast.h"
#import "Tool.h"
#import "QAir.h"
#import <AudioToolbox/AudioToolbox.h>
@interface QAirAppDelegate ()

@end

@implementation QAirAppDelegate

- (NSMutableArray *)peripherals{
    if (!_peripherals) {
        _peripherals = [[NSMutableArray alloc]init];
    }
    return _peripherals;
}

- (MFSideMenuContainerViewController *)container{
    if (!_container) {
        MainViewController *mainVC = [[UIStoryboard storyboardWithName:@"SideBar" bundle:nil]instantiateViewControllerWithIdentifier:@"Main"];
        SideBarLeftViewController *sideLeft = [[UIStoryboard storyboardWithName:@"SideBar" bundle:nil] instantiateViewControllerWithIdentifier:@"SideBarLeft"];
        _container = [MFSideMenuContainerViewController containerWithCenterViewController:mainVC
                                                                                                     leftMenuViewController:sideLeft
                                                                                                    rightMenuViewController:nil];
        _container.leftMenuWidth = SCREEN_WIDTH - 100;
    }
    return _container;
}

- (LoadingViewController *)loadingView{
    if (!_loadingView) {
        _loadingView = [[UIStoryboard storyboardWithName:@"Loading" bundle:nil] instantiateViewControllerWithIdentifier:@"Loading"];
    }
    return _loadingView;
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH , SCREEN_HEIGH)];
    

    //蓝牙模块连接
    self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:nil];

    //判断是否第一次进入
    if (![Config getFirstEnter]) {
        [Config setFirstEnter];
        self.window.rootViewController = self.loadingView;
    }else{
        self.window.rootViewController = self.container;
    }
    
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)stopScan{
    [self.centralManager stopScan];
}

- (void)startScan{
    [self.centralManager stopScan];
    [self.peripherals removeAllObjects];
    [self.centralManager scanForPeripheralsWithServices:nil options:nil];
}

- (void)connectToPeripheral:(CBPeripheral *)peripheral{
    [self.centralManager connectPeripheral:peripheral options:nil];
}

- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
    switch(central.state) {
        case CBCentralManagerStatePoweredOn:
        {
            [self startScan];
        }
            break;
            
        case CBCentralManagerStatePoweredOff:
        {
            [self.window makeToast:@"蓝牙未开启" duration:2.0 position:CSToastPositionBottom];
        }
            break;
        case CBCentralManagerStateUnsupported:
        {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"警告" message:@"不支持蓝牙设备" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
            [alert show];
        }
            break;
            
        default:
            break;
    }
}

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
    if ([peripheral.name containsString:DEVICE_NAME_FILTER] && ![self.peripherals containsObject:peripheral]) {
        [self.peripherals addObject:@{kKeyNotificationUserInfoPeripherals:peripheral,
                                      kKeyNotificationUserInfoRSSI:RSSI}];
        [Tool peripheralsDidUpdates:self.peripherals];
    }
}

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
    peripheral.delegate = self;
    [peripheral discoverServices:@[[CBUUID UUIDWithString:SERVICES_UUID]]];
}

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    [self.window makeToast:@"蓝牙已经断开" duration:2.0 position:CSToastPositionBottom];
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    if (error) {
        [self.window makeToast:@"蓝牙连接错误" duration:2.0 position:CSToastPositionBottom];
    }else{
        for (CBService *service in peripheral.services) {
            if ([SERVICES_UUID containsString:[service.UUID.UUIDString lowercaseString]]) {
                CBUUID *get_data_characteristci_uuid = [CBUUID UUIDWithString:GET_DATA_CHARACTERISTIC_UUID];
                [peripheral discoverCharacteristics:@[get_data_characteristci_uuid]
                                         forService:service];
                self.qairPeripheral = peripheral;
            }
        }
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    if (error) {
        [self.window makeToast:@"蓝牙连接错误" duration:2.0 position:CSToastPositionBottom];
    }else{
       for (CBCharacteristic *characteristic in service.characteristics) {
           //第一次获取数据
           if ([GET_DATA_CHARACTERISTIC_UUID containsString:[characteristic.UUID.UUIDString lowercaseString]]) {
               [peripheral setNotifyValue:YES forCharacteristic:characteristic];
           }
           
           //获取历史
           if ([GET_HISTORY_CHARACTERISTIC_UUID containsString:[characteristic.UUID.UUIDString lowercaseString]]) {
               [peripheral setNotifyValue:YES forCharacteristic:characteristic];
               [peripheral writeValue:self.historyWriteData forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
           }
        
        }
    }
    
}

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    if (error) {
        [self.window makeToast:@"蓝牙连接错误" duration:2.0 position:CSToastPositionBottom];
        return;
    }
    //获取数据
    if ([GET_DATA_CHARACTERISTIC_UUID containsString:[characteristic.UUID.UUIDString lowercaseString]]) {
        NSData *returnData = characteristic.value;
        
        NSString *air = [NSString stringWithFormat:@"%@",[Tool getData:returnData atStart:8]];
        NSString *hcho = [NSString stringWithFormat:@"%.2f",[[Tool getData:returnData atStart:6] floatValue]/100];
        NSString *pm25 = [NSString stringWithFormat:@"%@",[Tool getData:returnData atStart:4]];
        NSString *humidity = [NSString stringWithFormat:@"%@",[Tool getData:returnData atStart:2]];
        NSString *temperature = [NSString stringWithFormat:@"%@",[Tool getData:returnData atStart:0]];
        QAir *qair = [[QAir alloc] initWithAir:air
                                         hcho:hcho
                                         pm25:pm25
                                     humidity:humidity
                                  temperature:temperature
                                        noise:@""];
        NSNotification *updateQairNotification = [NSNotification notificationWithName:UPDATE_QAIR_NOTIFICATION_NAME
                                                                               object:nil
                                                                             userInfo:@{@"QAir":qair}];
        [[NSNotificationCenter defaultCenter]postNotification:updateQairNotification];
    }
    
    if ([GET_HISTORY_CHARACTERISTIC_UUID containsString:[characteristic.UUID.UUIDString lowercaseString]]) {
        NSData *returnData = characteristic.value;
        NSData *returnHeadData = [returnData subdataWithRange:NSMakeRange(0, 1)];
        NSMutableArray *historyData = [[NSMutableArray alloc]init];
        //获取最后一段数据 00,01,...,0f
        if ([[Tool dataToHexString:returnHeadData] isEqualToString:@"0f"]) {
            for (NSUInteger index=0; index<9; index++) {
                if ([Tool getData:returnData atStart:index*2+1] != nil) {
                    [historyData addObject:[Tool getData:returnData atStart:index*2+1]];
                }
            }
            NSNotification *qAirHistoryNotification = [NSNotification notificationWithName:HISTORY_DATA_NOTIFICATION_NAME
                                                                                    object:nil
                                                                                  userInfo:@{@"history":historyData}];
            [[NSNotificationCenter defaultCenter]postNotification:qAirHistoryNotification];
        }
    }
    
    
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
